Table of Contents
Objects
An important characteristic of the Python language is the consistency of its object model. Every number, string, data structure, function, class, module, etc. exists in the Python interpreter as a Python object. Each object has an associated type (e.g. string, integer or function) and internal data. In practice this makes the language very flexible, as even functions can be treated like any other object.
Variables
In Python, a variable is a name that you assign to an object by using the equal sign (=
). We can think of variables as labels that we assign to values.
Example
In this example, the variablea
is assigned to the object 1 and the variable b
is assigned to object the 2. To add the two integer objects, we simply add the variables.
1a=1
2b=2
3print(a)
4print(b)
5print(a+b)
1
2
3
In Python, you change a variable’s type simply by assigning it to a new object. This is referred to as dynamic typing. In the following, the variable a
is first assigned to the integer object with value 10. It is then assigned to the string object ’ten'.
1a=10
2a
10
We now compute the data type of the object using the type
function. We will discuss Python data types in more detail in the next section.
1type(a)
int
We now assign a
to the string ’ten'.
1a='ten'
2a
'ten'
1type(a)
str
We see that the same variable name a
can be assigned to objects of different data types at different times.
Dynamic Typing in Python: The type of a variable is allowed to change over its lifetime. More technically, the Python interpreter assigns variables a type only at runtime based on the variable's value at the time.
Python is case-sensitive, so a
and A
are two different variables. Variable names must follow certain rules:
- They must start with either a letter or an underscore.
- They must consist of letters, numbers, and underscores.
- Spaces are not allowed, but underscores can be used to separate words in variable names.
- Avoid using Python keywords and function names as variable names; that is, do not use words that Python has reserved for a particular purpose, such as the word
print
.
Attributes and Methods
In the context of objects, variables are called attributes and functions are called methods: attributes give you access to the data of an object, and methods allow you to perform an action. To access attributes and methods, you use the dot notation like this: myobject.attribute
and myobject.method()
.
Let’s take a concrete example: in a class of 20 students, each student is considered an object. Now, if we focus on a certain student called student1
, then the height of this student can be accessed using student1.height
where student1
is the object and height
is the attribute. Also, we can make student1
perform a certain action by calling, say, the jump
method student1.jump(10)
, which would make the student jump 10cm into the air.